import oss2
import time
import sys

souces_file = str(sys.argv[1])
target_file = str(sys.argv[2])


class log_uploader():
    def __init__(self, product_id):
        self.product_id = product_id
        self.access_key_id = "LTAI4G3TDZ8hz73Kv2JW7NyL"
        self.access_key_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
        self.endpoint = "oss-cn-hangzhou.aliyuncs.com"
        self.auth = oss2.Auth(self.access_key_id, self.access_key_secret)
        self.bucket = None
        self.bucket_product = oss2.Bucket(
            self.auth, self.endpoint, self.product_id)

    def uploadfile(self, logfileName, localpath):
        try:
            oss2.resumable_upload(self.bucket_product, logfileName, localpath)
            time.sleep(0.1)
            file_exist_check = self.bucket_product.object_exists(logfileName)
            if file_exist_check != True:
                return False
            else:
                print('upload success')
        except Exception as e:
            print('upload error :', e)
            return False
        return True

    def search(self, name):
        list = []
        num = 0
        times = time.time()
        for object_info in oss2.ObjectIterator(self.bucket_product, prefix=name):
            list.append(str(object_info.key))
        # print(time.time()-times)
        for i in list:
            print(i)
            num += 1
        print('num: ', num)
        return list

    def download(self, name):
        try:
            for object_info in oss2.ObjectIterator(self.bucket_product, prefix=name):
                print(object_info.key)
                if (self.bucket_product.get_object_to_file(object_info.key, object_info.key) != None):
                    print('download file success')
                    return True

            print('download file error')
            return False

        except:
            print('download file error')
            return False

    def delete(self, name):
        try:
            for object_info in oss2.ObjectIterator(self.bucket_product, prefix=name):
                print(object_info.key)
                if (self.bucket_product.delete_object(object_info.key) != None):
                    print('delete file success')
                    return True

            print('delete file error')
            return False

        except:
            print('delete file error')
            return False


if __name__ == '__main__':
    up = log_uploader('test-log-fresh')
    up.uploadfile(souces_file, target_file)
    up.search(target_file)
    # up.search('102991698_BVAH202314000001')
